<?php

namespace app\admin\controller\business;

// 引入基类控制器
use app\common\controller\Backend;

class Busrecyclebin extends Backend
{
  // 设置关联查询
  protected $relationSearch = true;

  protected $AdminModel = null;

  public function __construct()
  {
    parent::__construct();

    $this->model = model('Business.Business');
    $this->AdminModel = model('Admin');
  }

  public function index()
  {
    if ($this->request->isAjax()) {
      // 过滤请求参数中的html标签和取消两边你空白
      $this->request->filter(['strip_tags', 'trim']);
      // 获取查询参数
      list($where, $sort, $order, $offset, $limit) = $this->buildparams();

      $total = $this->model
        ->onlyTrashed()
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->count();

      $list = $this->model
        ->onlyTrashed()
        ->with(['source', 'admin'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      // var_dump($this->model->getLastSql());
      // exit;

      $result = [
        'rows' => $list,
        'total' => $total
      ];

      return json($result);
    }

    return $this->view->fetch();
  }

  // 还原
  public function restore($ids = null)
  {
    if ($this->request->isAjax()) {
      if (!$ids) {
        $this->error('缺少参数');
        exit;
      }

      $list = $this->model->onlyTrashed()->whereIn('id', $ids)->select();

      if (!$list) {
        $this->error(__('No Results were found'));
        exit;
      }

      // 设置删除时间为 null
      $result = $this->model->onlyTrashed()->whereIn('id', $ids)->update(['deletetime' => null]);

      if ($result) {
        $this->success('还原成功');
      } else {
        $this->error('还原失败');
      }
    }
  }

  // 销毁
  public function destroy($ids = null)
  {
    if ($this->request->isAjax()) {
      if (!$ids) {
        $this->error('缺少参数');
        exit;
      }

      $list = $this->model->onlyTrashed()->whereIn('id', $ids)->select();

      if (!$list) {
        $this->error(__('No Results were found'));
        exit;
      }

      // 删除数据
      $result = $this->model->onlyTrashed()->whereIn('id', $ids)->delete(true);

      if ($result) {
        $this->success('销毁成功');
      } else {
        $this->error('销毁失败');
      }
    }
  }
}
